//
//  BCLocationInterceptorManager.m
//  BanChinaTest
//
//  Created by Ann on 2024/3/11.
//

#import "BCLocationInterceptorManager.h"
#import <CoreLocation/CoreLocation.h>

@interface BCLocationInterceptorManager ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation BCLocationInterceptorManager

+ (BCLocationInterceptorManager *)sharedManager {
    static BCLocationInterceptorManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self checkLocationInChina];
    }
    return self;
}

- (void)checkLocationInChina {
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks firstObject];
        NSString *countryCode = placemark.ISOcountryCode;
        BOOL inside = NO;
        if ([countryCode isEqualToString:@"CN"]) {
            NSLog(@"用户在中国大陆");
            inside = YES;
        } else {
            NSLog(@"用户不在中国大陆");
            inside = NO;
        }
        if (self.delegate && [self.delegate respondsToSelector:@selector(locationInterceptorManager:didCheckLocationInChinaFinished:)]) {
            [self.delegate locationInterceptorManager:self didCheckLocationInChinaFinished:inside];
        }
    }];
    
    [self.locationManager stopUpdatingLocation];
}

@end
 
